<template>
  <div class="editor-canvas" @click="clearSelection">
    <div class="canvas-container">
      <draggable class="drag-area" :list="canvasComponents" group="components">
        <div 
          v-for="(element, index) in canvasComponents" 
          :key="element.id" 
          class="canvas-component" 
          @click.stop="selectComponent(element, index)"
          :class="{ selected: selectedIndex === index }"
        >
          <component :is="element.type" v-bind="element.props" />
        </div>
      </draggable>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { EventBus } from '@/event-bus.js';
import TitleBar from './editor-components/TitleBar.vue'
import TextComponent from './editor-components/Text.vue'
import ButtonComponent from './editor-components/Button.vue'

export default {
  name: 'EditorCanvas',
  components: {
    draggable,
    'title-bar': TitleBar,
    'text': TextComponent,
    'button': ButtonComponent
  },
  data() {
    return {
      canvasComponents: [],
      selectedIndex: null
    }
  },
  created() {
    EventBus.$on('component-updated', this.updateComponent);
  },
  beforeDestroy() {
    EventBus.$off('component-updated', this.updateComponent);
  },
  methods: {
    selectComponent(component, index) {
      this.selectedIndex = index;
      EventBus.$emit('component-selected', component);
    },
    clearSelection() {
      this.selectedIndex = null;
      EventBus.$emit('component-selected', null);
    },
    updateComponent(updatedComponent) {
      const index = this.canvasComponents.findIndex(c => c.id === updatedComponent.id);
      if (index !== -1) {
        this.$set(this.canvasComponents, index, updatedComponent);
      }
    }
  }
}
</script>

<style scoped>
.editor-canvas {
  flex: 1;
  padding: 20px;
  background-color: #f0f2f5;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}
.canvas-container {
    width: 375px;
    height: 667px;
    background-color: white;
    border: 1px solid #ccc;
    overflow-y: auto;
}
.drag-area {
  min-height: 100%;
}
.canvas-component {
  padding: 5px;
  border: 1px dashed #ccc;
  margin: 5px;
  cursor: move;
}
.canvas-component.selected {
  border: 2px solid #409EFF;
}
</style>